package com.java2007.hotel.dao.impl;

import com.java2007.hotel.dao.AdminDao;
import com.java2007.hotel.pojo.Admin;
import com.java2007.hotel.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author csl
 * @version V1.0
 * @date 2021/01/21
 **/
public class AdminDaoImpl implements AdminDao {

    /**
     * 增加一个管理员
     * @param admin
     * @return
     */
    @Override
    public int addAdmin(Admin admin) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "INSERT INTO t_admin\n" +
                "            (admin_name,\n" +
                "             admin_pwd,\n" +
                "             admin_status,\n" +
                "             admin_create_date,\n" +
                "             admin_update_date,\n" +
                "             admin_phone,\n" +
                "             admin_email,\n" +
                "             admin_role)\n" +
                "VALUES (?,?,?,?,?,?,?,?)";
        int update = queryRunner.update(JdbcUtils.getConnection(), sql, admin.getName(), admin.getPwd(),
                admin.getStatus(), admin.getCreateDate(), admin.getUpdateDate(), admin.getPhone(),
                admin.getEmail(), admin.getRole());
        return update;
    }

    /**
     * 根据名字查找一个管理员
     * @param name
     * @return
     */
    @Override
    public Admin selectByName(String name) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "SELECT\n" +
                "  admin_id id,\n" +
                "  admin_name name,\n" +
                "  admin_pwd pwd,\n" +
                "  admin_status status,\n" +
                "  admin_create_date createDate,\n" +
                "  admin_update_date updateDate,\n" +
                "  admin_phone phone,\n" +
                "  admin_email email,\n" +
                "  admin_role role\n" +
                "FROM t_admin\n" +
                "WHERE admin_name = ?";
        Admin query = queryRunner.query(sql, new BeanHandler<Admin>(Admin.class), name);
        return query;
    }
}
